<script setup>
import { onMounted, onUnmounted, ref, watchEffect } from 'vue'
import * as echarts from 'echarts'

let chart = null
const chartRef = ref(null)

const props = defineProps({
  chartOptions: Object
})

const initChart = () => {
  chart = echarts.init(chartRef.value)
}
const setOption = (option = props.chartOptions) => {
  chart.setOption(option, true)
}
onMounted(() => {
  initChart()
  setOption()
  watchEffect(() => {
    setOption()
  })
  // 监听窗口的 resize 事件
  const resizeHandler = () => {
    if (chart != null) {
      try {
        setOption()
        chart.resize()
      } catch (error) {
        console.error('Resize error:', error)
      }
    }
  }
  window.addEventListener('resize', resizeHandler)
  // 组件卸载时移除事件监听器
  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler)
    if (chart != null) {
      chart.dispose()
    }
  })
})
</script>

<template>
  <div class="chart" ref="chartRef"></div>
</template>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
